package com.zyb.beiojbackendjudgeservice.mq;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.zyb.beiojbackendjudgeservice.service.JudgeService;
import com.zyb.beiojmodel.model.mq.ExecuteCodeMessage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 十八岁讨厌编程
 * @date 2025/3/17 9:55
 * @PROJECT_NAME beioj-backend-microservice
 * @description  消息消费者
 */

@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private JudgeService judgeService;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("判题服务接收消息：{}", message);
        ExecuteCodeMessage codeMessage = JSONUtil.toBean(message, ExecuteCodeMessage.class);
        Long questionSubmitId = codeMessage.getQuestionSubmitId();
        Long userId = codeMessage.getUserId();
        try {
            judgeService.doJudge(questionSubmitId,userId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }

}